﻿using UnityEngine;
using UnityEngine.Rendering;

public class DepthCamera : MonoBehaviour
{
    private RenderTexture depthRT;
    private RenderTexture depthTex;

    private CommandBuffer _cbDepth = null;

    private Camera _Camera = null;

    private void Awake()
    {
        _Camera = GetComponent<Camera>();
        int Width = _Camera.pixelWidth;
        int Height = _Camera.pixelHeight;

        depthRT = new RenderTexture(Width, Height, 24, RenderTextureFormat.Depth);


        depthTex = new RenderTexture(Width, Height, 0, RenderTextureFormat.RHalf);

        _cbDepth = new CommandBuffer();
        _cbDepth.Blit(depthRT.depthBuffer, depthTex.colorBuffer);
        _Camera.AddCommandBuffer(CameraEvent.AfterForwardOpaque, _cbDepth);

    }

    private void Update()
    {
        Shader.SetGlobalTexture("_CameraDepthTexture", depthTex);
    }

    void OnPreRender()
    {
        _Camera.SetTargetBuffers(depthTex.colorBuffer, depthRT.depthBuffer);
    }
}
